package main

import (
	"archive/zip"
	"flag"
	"fmt"
	"goDFS/etc"
	"goDFS/public"
	"goDFS/storage"
	"goDFS/tracker"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

var (
	nc      string //新建一个conf.init
	conf    string //声明conf地址
	serType string
)

//绑定命令行参数
func init() {
	flag.StringVar(&nc, "nc", "", "Initializes a default configuration file."+
		"The output address needs to be specified")

	flag.StringVar(&conf, "conf", "./goDFS.conf", "Specifies the configuration file to start the service")
	flag.StringVar(&serType, "type", "", "Use type to specify a service type. The value can only be tracker or storage")

	flag.Parse()
}

var confJson = `
{
  "storage": {
    "group_path": "./",
    "log_path": "./"
  },
  "tracker": {
    "port": 80,
    "token_pwd": "%s",
    "host": "0.0.0.0",
	"web": "./web"
  }
}
`

func DownLoadWeb(t *etc.Tracker) {

	//下载静态文件

	zipPath := fmt.Sprintf("%s/%s", t.Web, "www.zip")
	if _, err := os.Stat(zipPath); err == nil {
		return
	}

	url := "https://gitee.com/timedb/goDFS/raw/master/etc/www/www.zip"
	res, err := http.Get(url)
	if err != nil {
		fmt.Println(err) //main文件不需要写到日志中
		return
	}

	//保存io
	defer res.Body.Close()
	buf, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	//保存zip

	f, err := os.Create(zipPath)
	if err != nil {
		fmt.Println(err)
		return
	}
	f.Write(buf)
	f.Close()

	r, err := zip.OpenReader(zipPath)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer r.Close()

	for _, k := range r.Reader.File {
		if k.FileInfo().IsDir() {
			err := os.MkdirAll(fmt.Sprintf("%s/%s", t.Web, k.Name), 0644)
			if err != nil {
				fmt.Println(err)
			}
			continue
		}
		r, err := k.Open()
		if err != nil {
			fmt.Println(err)
			continue
		}
		defer r.Close()
		NewFile, err := os.Create(fmt.Sprintf("%s/%s", t.Web, k.Name))
		if err != nil {
			fmt.Println(err)
			continue
		}
		io.Copy(NewFile, r)
		NewFile.Close()
	}

}

func main() {
	//新建配置文件
	if nc != "" {
		f, err := os.Create(nc)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		f.WriteString(fmt.Sprintf(confJson, public.RandomPwd()))
		return
	}

	if serType == "tracker" || serType == "storage" {
		//启动服务
		Conf := etc.LoadConfig(conf)

		//启动tracker
		if serType == "tracker" {
			trackerConf := Conf.GetTracker()
			err := etc.VerifyTracker(trackerConf)
			if err != nil {
				fmt.Println(err)
				return
			}
			//下载初始化界面
			if trackerConf.Web != "" {
				go DownLoadWeb(trackerConf)
			}

			//启动tracker
			tracker.Service(Conf)
			return

		}

		if serType == "storage" {
			storageConf := Conf.GetStorage()
			err := etc.VerifyStorage(storageConf)
			if err != nil {
				fmt.Println(err)
				return
			}
			//下载初始化界面
			storage.CreteMkdir(storageConf) //创建group

			//启动tracker
			storage.Service(Conf)
			return

		}

	}

}
